﻿using BllFactory;
using ETWebApi2.Models;
using IBLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using ETWebApi2;
using System.Linq.Expressions;

namespace ETWebApi.Controllers
{
    [Route("myupload"), JwtAuthActionFilter]
    public class MyUploadFileController : ApiController
    {
        private IFiles_tbService m_fileService = ServiceFactory.CreatService<IFiles_tbService>();
        private ICUser_tbService m_userServer= ServiceFactory.CreatService<ICUser_tbService>();
        /// <summary>
        /// 分页加载我的上传文件  以及根据相关条件的查询 时间  文件名  接收方公司名称  接受人姓名
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>        
        [HttpGet]
        public HttpResponseMessage GetbyPara(string query, int page, int limit, DateTime? STime = null, DateTime? ETime = null)
        {

            if (ETime == null)
                ETime = DateTime.Now;
            if (STime == null)
                STime = Convert.ToDateTime("2000-01-01");
            JwtAuthObject info = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            CUser_tb currentUser = m_userServer.GetList(u => u.Id == info.UserId).FirstOrDefault();

            string QuerySql = "";
            //关键字对上传的文件名、接收方公司名的搜索有效   
            if (!string.IsNullOrEmpty(query))
            {
                QuerySql += string.Format("and (Files_tb.Attachment like '%{0}%' or Files_tb.CompanyId in(select Id from Customers_tb where Customers_tb.Name like '%{0}%') or FileDownLoadLog_tb.DUser in(select Id from CUser_tb where CUser_tb.UserName like '%{0}%') )", query);
            }
            //搜索时间  
            QuerySql += string.Format("and Time >='{0}' and Time<'{1}'", STime, ETime);
            QuerySql = string.Format("select distinct Files_tb.Id,Files_tb.Attachment,Files_tb.IsValid,Files_tb.CompanyId,Files_tb.Time ,Files_tb.dIP,Files_tb.dTime from Files_tb inner join FileDownLoadLog_tb on Files_tb.id=FileDownLoadLog_tb.FileId  where UploadUserId={0} {1}", currentUser.Id, QuerySql);

            List<MyUploadShowBase> files = new List<MyUploadShowBase>();
            int total = 0;
            using (var context = new MyETLockContext())
            {
                var res = context.Database.SqlQuery<object>(QuerySql);
                total = res.Count();
                if (res != null)
                {
                    int start = (page - 1) * limit;
                    int end = page * limit;
                    QuerySql = string.Format("select * from (select row_number()over(order by a.Time desc)rownumber,* from ({0}" + ")a )b where rownumber between {1} and {2}", QuerySql, start+1, end);
                    files = context.Database.SqlQuery<MyUploadShowBase>(QuerySql).ToList();
                }
            }

            if (files.Count > 0)
            {
                List<MyUploadShow> myshow = new List<MyUploadShow>();               
                for (int i = 0; i < files.Count; i++)
                {
                    int counts = 0;
                    new BaseClass().TotalCount(ref counts, files[i].Id);
                    MyUploadShow my = new MyUploadShow()
                    {
                        Id = files[i].Id,
                        FileName = files[i].Attachment,
                        IsValid = files[i].IsValid,
                        CompanyName = new BaseClass().GetCompanyName(files[i].CompanyId),
                        DownNum = counts,
                        IP = files[i].dIP,
                        Time = Convert.ToDateTime((files[i].Time)).ToString("yyyy-MM-dd"),
                        DownloadTime = Convert.ToDateTime((files[i].dTime)).ToString("yyyy-MM-dd"),
                    };
                    myshow.Add(my);
                }
                return ObjectToJson.toJson(new { status = 200, data = new { total = total, rows = myshow } });
            }
            else
                return ObjectToJson.toJson(new { status = 201, data = new { total = 0, rows = 0 } });
        }

        /// <summary>
        /// 是否允许用户下载
        /// </summary>
        /// <param name="obj">id文件id IsValid是否允许下载</param>
        /// <returns> </returns>
        [HttpPut]
        public HttpResponseMessage PutIsDownLoad(dynamic obj)
        {
            HttpResponseMessage hrm = new HttpResponseMessage();
            hrm = ObjectToJson.toJson(new { status=201,error= "缺少相关参数" });
            if (!string.IsNullOrEmpty(obj.id.ToString()) && !string.IsNullOrEmpty(obj.IsValid.ToString()))
            {
               Files_tb file = m_fileService.GetList(f=>f.Id==Convert.ToInt32(obj.id)).FirstOrDefault();
                file.IsValid = Convert.ToInt32(obj.IsValid);
                if (m_fileService.Update(file))
                    hrm = ObjectToJson.toJson(new { status = 200, error = "成功" });
                else
                    hrm = ObjectToJson.toJson(new { status = 201, error = "操作失败" });
            }
            return hrm;
        }

        private string GetNameById(int uid)
        {
            return m_userServer.GetList(u=>u.Id==uid).FirstOrDefault().UserName;
        }
    }
}
